package com.example.security.decision;

import com.example.dao.RolePermission;

import com.example.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Jimmy
 * Date: 2020/3/9
 * Description:角色权限缓存数据
 */
@Configuration
public class UrlPermissionData {
    /**
     * 角色权限mapper
     */
    @Autowired
    private PermissionService permissionService;
    /**
     * 每一个资源所需要的角色
     */
    private static HashMap<String, Collection<ConfigAttribute>> map =null;
    public void loadResourceDefine(){
        map = new HashMap<>();
        //权限资源 和 角色对应的表  也就是 角色 权限中间表
        List<RolePermission> rolePermissons = permissionService.findAllRolePermission();

        //每个资源 所需要的权限
        for (RolePermission rolePermisson : rolePermissons) {
            String patchString = rolePermisson.getPatchString();
            String roleName = rolePermisson.getRoleName();
            ConfigAttribute role = new SecurityConfig(roleName);
            if(map.containsKey(patchString)){
                map.get(patchString).add(role);
            }else{
                map.put(patchString,new ArrayList<ConfigAttribute>(){{
                    add(role);
                }});
            }
        }
    }
    public Map<String, Collection<ConfigAttribute>> getMap(){
        if(map==null){
            loadResourceDefine();
        }
        return map;
    }
}
